package client.auction;

/**
 * This class handles the notifications from the server.
 * If i.e. a bidder was overbid by another bidder the server sends a
 * notification to the client by a udp-datagrampacket. Therefore the client
 * has to wait (blocking) for these notifications, which is handled
 * with this thread.
 *
 * @version 1.0 vom 18.10.2012
 * @author Peter Tillian 1026312
 */

import java.io.IOException;
import java.net.DatagramSocket;
import java.net.DatagramPacket;
import java.net.SocketException;

public class AuctionClientNotificationThread extends Thread {

	private DatagramSocket socket = null;

	public AuctionClientNotificationThread(int udpPort) {
		super("ClientNotificationThread");
		try {
			socket = new DatagramSocket(udpPort);
		} catch (SocketException e) {
			System.err.println("Error creating DatagramSocket in "
					+ this.getClass() + ": " + e.getMessage());
		}
	}

	public void run() {
		while (true) {
			try {
				byte[] buf = new byte[256];
				DatagramPacket packet = new DatagramPacket(buf, buf.length);
				this.socket.receive(packet); // receive and show notification
												// from server.
				System.out.println(new String(packet.getData(), 0, packet
						.getLength()));

			} catch (IOException e) {
				if (!this.socket.isClosed()) {
					System.err
							.println("Error, receiving Datagramm-packet from server: "
									+ e.getMessage());
				} else {
					break;
				}
			}
			// if this thread is interrupted while not in a blocked-state.
			if (this.isInterrupted()) {
				this.interrupt();
			}
		}
	} // end run()

	@Override
	public void interrupt() {
		this.socket.close();
		super.interrupt();
	}

} // end of class ClientNotificationThread